<template>
  <div class="box">
    <van-nav-bar
      title="个人资料"
      left-arrow
      @click-left="$router.push('/my')"
    />
    <div class="userAvatar">
      <van-uploader :max-size="500 * 500" :max-count="1" :after-read="readOk" @oversize="onOversize">
          <van-image
            round
            width="100"
            height="100"
            :src="avatar"
          />
      </van-uploader>
      <h4>点击修改头像</h4>
    </div>
    <div class="userMsg">
      <van-form @submit="onSubmit">
        <van-field
          v-model="userName"
          label="用户名"
          name="userName"
          readonly
        />
        <van-field
          v-model="nickName"
          type="text"
          name="nickName"
          label="昵称"
          placeholder="请输入昵称"
        />
        <van-field
          v-model="passWord"
          type="password"
          name="passWord"
          label="密码"
          placeholder="请输入密码"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" class="btn">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { getUser, setUserAvatar, setUser } from '@/api/request.js'
import Vue from 'vue'
import { NavBar, Uploader, Toast, Image as VanImage, Form, Field, Button } from 'vant'

Vue.use(NavBar)
Vue.use(Uploader)
Vue.use(Toast)
Vue.use(VanImage)
Vue.use(Field)
Vue.use(Form)
Vue.use(Button)

export default {
  // beforeRouteEnter (to, from, next) {
  //   if (sessionStorage.getItem('isLogin') === 'ok') {
  //     next()
  //   } else {
  //     next('/login')
  //   }
  // },
  data () {
    return {
      avatar: '',
      userMsg: {},
      userName: '',
      passWord: '',
      nickName: ''
    }
  },
  mounted () {
    getUser({
      id: sessionStorage.getItem('userId')
    }).then(data => {
      console.log(data.data)
      this.avatar = data.data.msg.avatar
      this.userMsg = data.data.msg
      this.userName = this.userMsg.userName
    })
  },
  methods: {
    onOversize (f) {
      console.log(f)
      Toast('请上传 500 x 500 像素的图片')
    },
    readOk (f) {
      console.log(f.content)
      setUserAvatar({
        id: sessionStorage.getItem('userId'),
        avatar: f.content
      }).then(data => {
        this.avatar = data.data.msg
      })
    },
    onSubmit (v) {
      console.log(v)
      setUser({
        id: sessionStorage.getItem('userId'),
        msg: JSON.stringify(v)
      }).then(data => {
        console.log(data.data)
        this.$router.push('/my')
      })
    }
  }
}
</script>

<style lang="scss">
.userAvatar{
  text-align: center;
  .van-uploader{
    margin: 0.4rem 0 0.05rem;
  }
  h4{
    font-weight: 500;
    margin-bottom: 0.3rem;
  }
}
.van-cell{
  margin: 0.1rem 0;
}
.btn{
  margin-top: 0.3rem;
}
</style>
